<?php
namespace app\api\controller;
use think\Log;
/**
 * http类型为 Application/json, 非XMLHttpRequest的application/x-www-form-urlencoded, $_POST方式是不能获取到的，
 * APP ID和Master Secret可以在https://beecloud.cn平台登录后获取
 *
 * 备注：secret是一个非常重要的数据，请您必须小心谨慎的确保此数据保存在足够安全的地方。
 *      您从BeeCloud官方获得此数据的同时，即表明您保证不会被用于非法用途和不会在没有得到您授权的情况下被盗用，
 *      一旦因此数据保管不善而导致的经济损失及法律责任，均由您独自承担。
 */
class Webhook
{
    public function callback()
    {
        $appId = config('beecloud.app_id');
        $masterSecret = config('beecloud.master_secret');
        $jsonStr = file_get_contents("php://input");
        Log::record("Webhook callback jsonStr = ".$jsonStr);

        $msg = json_decode($jsonStr);

        //第一步:验证签名
        $sign = md5($appId . $msg->transaction_id . $msg->transaction_type . $msg->channel_type . $msg->transaction_fee.$masterSecret);
        Log::record("Webhook callback sign = ".$sign);

        if ($sign != $msg->signature) {
            // 签名不正确
            Log::record("Webhook callback 签名不正确");
            exit();
        }

        //第二步:过滤重复的Webhook
        $order = model('Order')->get(['bill_no'=>$msg->transaction_id]); 
        Log::record("Webhook callback order = ".print_r($order,1));

        if(!$order || $order['paid']){
          exit();
        }
        
        Log::record("Webhook callback transaction_fee = ".$msg->transaction_fee);
        Log::record("Webhook callback total_fee = ".$order['total_fee']);
        Log::record("Webhook callback transaction_type = ".$msg->transaction_type);
        Log::record("Webhook callback trade_success = ".$msg->trade_success);
        //第三步:验证订单金额与购买的产品实际金额是否一致
        //也就是验证调用Webhook返回的transaction_fee订单金额是否与客户服务端内部的数据库查询得到对应的产品的金额是否相同
        if($msg->transaction_fee != $order['total_fee']){
            exit();
        }

        //第四步:处理业务逻辑和返回
        /*
         * 推送支付的结果
         */
        if($msg->transaction_type == "PAY") {
            //付款信息
            //支付状态是否变为支付成功,true代表成功
            if($msg->trade_success)
            {
                $data['paid'] = 1;
                switch ($order['type']) {
                    case '1':
                        // 活动报名成功
                        return $this->travelMemberBusiness($order);
                        break;
                    case '2':
                        // 支付社群会费成功
                        return $this->communityBusiness($order);
                        break;
                    case '3':
                       // 海外游学支付尾款
                        return $this->tailBusiness($order);
                        break;
                    case '4':
                       // 发布活动支付定金
                        return $this->travelBusiness($order);
                        break;
                    case '5':
                       // 社群/用户充值
                        return $this->recharge($order,2);
                        break;
                    case '6':
                       // 社群/用户提现
                        return $this->withdrow($order,2);
                        break;
                    case '7':
                       // 供应商充值
                        return $this->recharge($order,1);
                        break;
                    case '8':
                       // 供应商提现
                        return $this->withdrow($order,1);
                        break;
                    default:
                        # code...
                        break;
                }
            }
           
            model('Order')->save($data,['id' => $order['id']]); // 保存订单
            
        } else if ($msg->transaction_type == "REFUND") { //退款的结果
            $data['paid'] = 3;
            switch ($order['type']) {
                case '1':
                    $travelMember = model('travelMember')->get(['id'=>$order['good_id']]);
                    $travelMember->save($data,['id' => $travelMember['id']]);
                    $travel = model('Travel')->get($travelMember['travel_id']);
                    $user = model('User')->get(['id'=>$travelMember['member_id']]);
                    $sponsor = model('User')->get(['id'=>$travel['sponsor']]);
                    jpush(1,$sponsor['mobile'],$user['name'].'取消报名活动【'.$travel['titles'].'】，退款成功');
                    paylog(2,$user['id'],'取消报名',$travel['titles'],0);
                    model('TravelMember')->where(['travel_id'=>$travel_id,'member_id'=>$this->user['id']])->delete();
                    break;
                case '4':
                    # 活动结束，退还定金
                    $travel  = model('Travel')->get($order['good_id']);
                    $sponsor = model('User')->get($travel['sponsor']);
                    $result  = model('TravelDistribution')->where(['travel_id'=>$travel['id'],'user_id'=>$sponsor['id']])->find();
                    if($result)
                    {
                        model('TravelDistribution')
                            ->where(['travel_id'=>$travel['id'],'user_id'=>$sponsor['id']])
                            ->update(['paid'=>1]);
                    }
                    break;
                default:
                    # code...
                    break;
            }
            
            $order->save($data,['id' => $order['id']]); // 保存订单       
        }

        /*
         * 推送企业打款结果的
         * transaction_id就是企业打款的交易单号, 对应支付请求的bill_no, transaction_type为TRANSFER, sub_channel_type为BC_TRANSFER
         * message_detail中包含打款相关的详细信息
         *
         */
        if ($msg->transaction_type == "TRANSFER") {
            //企业打款状态是否为成功,true代表成功
            $status = $msg->trade_success;

            if($status)
            {
                $data['paid'] = 1;
                model('TravelDistribution')->where(['id'=>$order['id']])->update(['paid'=>1]);
                $order->save($data,['id' => $order['id']]); // 保存订单       

            }

            //message_detail 参考文档
            switch ($msg->channel_type) {
                case "BC":
                    if($msg->sub_channel_type == 'BC_TRANSFER'){
                        //message_detail中包含打款相关的详细信息
                        //TODO...
                    }
                    break;
            }
        }

        /*
         * 推送订阅结果的
         * transaction_id就是创建订阅时返回的订阅id，transaction_type为SUBSCRIPTION，sub_channel_type为BC_SUBSCRIPTION，
         * message_detail中包含用户相关的注册信息，其中的card_id注意留存。
         * 该id由{bank_name、card_no、id_name、id_no、mobile}共同决定，可以直接用于发起订阅
         */
        if ($msg->transaction_type == "SUBSCRIPTION") {
            //创建的订阅状态是否为成功,true代表成功
            $status = $msg->trade_success;

            //message_detail 参考文档
            switch ($msg->channel_type) {
                case "BC":
                    if($msg->sub_channel_type == 'BC_SUBSCRIPTION'){
                        //message_detail中包含签约相关的详细信息，包括card_id
                        //TODO...
                    }
                    break;
            }
        }

        /*
         * 推送代扣签约结果的
         * transaction_id就是代扣签约返回的id，transaction_type为SIGN，sub_channel_type为BC_CARD_CHARGE，
         * message_detail中包含签约相关的详细信息，其中的card_id注意留存。
         */
        if ($msg->transaction_type == "SIGN") {
            //创建的代扣签约状态是否为成功,true代表成功
            $status = $msg->trade_success;

            //message_detail 参考文档
            switch ($msg->channel_type) {
                case "BC":
                    if($msg->sub_channel_type == 'BC_CARD_CHARGE'){
                        //message_detail中包含签约相关的详细信息，包括card_id
                        //TODO...
                    }
                    break;
            }
        }

        //打印所有字段,仅供调试使用
        print_r($msg);

        //处理消息成功,不需要持续通知此消息返回success
        echo 'success';
    }  

    // 活动报名支付成功  业务逻辑处理
    public static function travelMemberBusiness($order)
    {
        $data['paid'] = 1;
        $travelMember = model('travelMember')->get(['id'=>$order['good_id']]);
        $travel = model('Travel')->get($travelMember['travel_id']);
        $title = "活动报名";
        $payFee = 0;
        if($travel['type'] == 1)
        {
            $data['paid'] = 2;
            $title .= "【定金】";
            $payFee = $travelMember['deposit'];
             // 活动报名支付成功，社群总收入、活动收入增加
            model('User')->where(['id'=>$travel['sponsor']])->setInc('sum_income',$travelMember['deposit']);
            model('User')->where(['id'=>$travel['sponsor']])->setInc('activity_income',$travelMember['deposit']);
        }
        else{
            $payFee = $travelMember['paid_fee'];
             // 活动报名支付成功，社群总收入、活动收入增加
            model('User')->where(['id'=>$travel['sponsor']])->setInc('sum_income',$travelMember['paid_fee']);
            model('User')->where(['id'=>$travel['sponsor']])->setInc('activity_income',$travelMember['paid_fee']);
        }

        if($order['channel_type'] == 'YE_APP')
        {
            // 减去余额
            model('User')->where(['id'=>$travelMember['member_id']])->setDec('wallet_money',$payFee);
        }

        model('travelMember')->save($data,['id'=>$order['good_id']]);

        if($travelMember['parentid'])
        {
            $travel = model('Travel')->get($travelMember['travel_id']);
            // 分享人总收入增加  佣金
            model('User')->where(['id'=>$travelMember['parentid']])->setInc('sum_income',$travel['commission']);
            model('UserCommission')->where(['travel_id'=>$travelMember['travel_id'],'user_id'=>$travelMember['parentid']])->setInc('commission',$travel['commission']);
        }

        // 用户活动报名 给社群提醒 【极光推送】
        $user = model('User')->get(['id'=>$travelMember['member_id']]);
        $sponsor = model('User')->get(['id'=>$travel['sponsor']]);
        jpush(1,$sponsor['mobile'],$user['name'].'成功报名了您发布的活动【'.$travel['titles'].'】');
        paylog(2,$user['id'],$title,$travel['titles'],1,$payFee);
    }

    // 海外游学尾款支付成功 业务逻辑处理代码
    public static function tailBusiness($order)
    {
        $data['paid'] = 1;
        $travelMember = model('travelMember')->get(['id'=>$order['good_id']]);
        if($order['channel_type'] == 'YE_APP')
        {
            // 减去余额
            model('User')->where(['id'=>$travelMember['member_id']])->setDec('wallet_money',$travelMember['paid_fee']);
        }

        $travel = model('Travel')->get($travelMember['travel_id']);

        // 活动报名支付成功，社群总收入、活动收入增加
        model('User')->where(['id'=>$travel['sponsor']])->setInc('sum_income',$travelMember['paid_fee']);
        model('User')->where(['id'=>$travel['sponsor']])->setInc('activity_income',$travelMember['paid_fee']);

        model('travelMember')->save($data,['id'=>$order['good_id']]);
        paylog(2,$user['id'],'活动报名【尾款】',$travel['titles'],1,$travelMember['paid_fee']);
    }

    // 支付社群会费成功业务逻辑处理
    public static function communityBusiness($order)
    {
        $data['paid'] = 1;
        $data['paidtime']=$data['entrytime'] = time();
        model('CommunityMember')->allowField(true)->save($data,['id'=>$order['good_id']]);

        $communityMember = model('communityMember')->get(['id'=>$order['good_id']]);
        $user = model('User')->get(['id'=>$communityMember['user_id']]);
        if($order['channel'] == 'YE_APP')
        {
            // 减去余额
            model('User')->where(['id'=>$user['id']])->setDec('wallet_money',$communityMember['fee']);
        }

        $community = model('User')->get(['id'=>$communityMember['community_id']]);

        // 总收入、会费收入
        $community->setInc('sum_income',$community['year_fee']);
        $community->setInc('wallet_money',$community['year_fee']);

        jpush(2,$community['mobile'],$user['name'].'认证费用已支付成功');
        paylog(2,$user['id'],'缴纳会费',$community['name'],1,$communityMember['fee']);
        paylog(2,$community['id'],'会员缴纳会费',$user['name']."加入".$community['name'],0,$communityMember['fee']);
    }

    // 发布活动定金支付成功  业务逻辑处理
    public static function travelBusiness($order)
    {
        // 将活动状态修改为 报名中
        $data['state'] = 2;
        // $travel = model('Travel')->get($order['travel_id']);
        $travel = model('Travel')->with('activity')->where(['id'=>$order['good_id']])->find();
        $travel->save($data,['id'=>$travel['id']]);

        if($order['channel'] == 'YE_APP')
        {
            // 减去余额
            model('User')->where(['id'=>$travel['sponsor']])->setDec('wallet_money',$order['total_fee']);
        }

        // 社群/用户发布活动 给供应商提醒 【极光推送】
        //$travel = TravelModel::with($join)->where(['id'=>$travel_id])->find();

        $sponsor = model('User')->get(['id'=>$travel['sponsor']]);
        foreach ($travel['activity'] as $k => $v) {
            $supplier = model('Supplier')->get($v['supplier_id']);
            jpush(1,$supplier['mobile'],$sponsor['name'].'发布了活动');
        }
        paylog(2,$travel['sponsor'],'组织活动定金',$travel['titles'],1,$order['total_fee']);
    }

    //充值
    public function recharge($order,$type)
    {
        $data = [
            'travel_id'=>0,
            'title'=>"充值",
            'type' => $type,
            'user_id'=>$order['good_id'],
            'fee'=>$order['total_fee'],
      ];
      model('TravelDistribution')->save($data);
      $user_model = $type==2?model('User'):model('Supplier');
      // 账户余额
      $user_model->where(['id'=>$order['good_id']])->setInc('wallet_money',$order['total_fee']);
      // paylog($type=2[1 供应商；2 社群/用户],$user_id,$title,$content,$mode=0[0 收入；1 支出]);
      paylog($type,$order['good_id'],'充值','当前账户余额',0,$order['total_fee']);
    }

    //提现
    public function withdrow($order,$type)
    {
        $data = [
            'travel_id'=>0,
            'title'=>"提现",
            'type' => $type,
            'user_id'=>$order['good_id'],
            'fee'=>$order['total_fee'],
            'mode'=>1,
      ];
      model('TravelDistribution')->save($data);
      $user_model = $type==2?model('User'):model('Supplier');
      // 账户余额
      $user_model->where(['id'=>$order['good_id']])->setDec('wallet_money',$order['total_fee']);
      // paylog($type=2[1 供应商；2 社群/用户],$user_id,$title,$content,$mode=0[0 收入；1 支出]);
      paylog($type,$order['good_id'],'提现','当前账户余额',1,$order['total_fee']);
    }
}


